﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;

namespace WcfInspectorLib
{
    /// <summary>
    /// 客户端消息拦截器
    /// </summary>
    public class ClientMessageInspector : IClientMessageInspector, IEndpointBehavior
    {
        /// <summary>
        /// 收到服务器回复之后
        /// </summary>
        public event EventHandler<AfterReceiveReplyEventArgs> AfterReceiveReply;
        /// <summary>
        /// 向服务器发送请求之前
        /// </summary>
        public event EventHandler<BeforeSendRequestEventArgs> BeforeSendRequest;

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(this);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {

        }

        public void Validate(ServiceEndpoint endpoint)
        {

        }

        void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (AfterReceiveReply == null) return;
            var args = new AfterReceiveReplyEventArgs(reply, correlationState);
            AfterReceiveReply(this, args);
        }

        object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (BeforeSendRequest != null)
            {
                var args = new BeforeSendRequestEventArgs(request, channel);
                BeforeSendRequest(this, args);
            }
            return null;
        }
    }
}
